<template>
    <div>
<!--      面包屑导航区域-->
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>权限管理</el-breadcrumb-item>
        <el-breadcrumb-item>角色列表</el-breadcrumb-item>
      </el-breadcrumb>
      <!--    卡片视图区域-->
      <el-card>
        <!--      添加角色按钮-->
        <el-row>
          <el-col>
            <el-button type="primary" @click="addRolesDialogVisible = true">添加角色</el-button>
          </el-col>
        </el-row>
        <el-table :data="rolesList" stripe border>
          <el-table-column type="expand">
            <template slot-scope="scope">
              <el-row :class="['bdbottom',i1 === 0? 'bdtop': '', 'vcenter']"
                      v-for="(item1, i1) in scope.row.children" :key="item1.id">
<!--                一级权限-->
                <el-col :span="5">
                  <el-tag closable @close="removeRightById(scope.row,item1.id)">{{item1.authName}}</el-tag>
                  <i class="el-icon-caret-right"></i>
                </el-col>
<!--                二级三级权限-->
                <el-col :span="19">
                  <el-row :class="[i2 ===0?'':'bdtop','vcenter']" v-for="(item2,i2) in item1.children" :key="item2.id">
<!--                    二级权限-->
                    <el-col :span="6">
                      <el-tag type="success" closable @close="removeRightById(scope.row,item2.id)">{{item2.authName}}</el-tag>
                      <i class="el-icon-caret-right"></i>
                    </el-col>
<!--                    三级权限-->
                    <el-col :span="18" >
                      <el-tag type="warning" closable @close="removeRightById(scope.row,item3.id)" v-for="item3 in item2.children" :key="item3.id">{{item3.authName}}</el-tag>
                    </el-col>
                  </el-row>
                </el-col>
              </el-row>
            </template>
          </el-table-column>
          <el-table-column type="index" label="序号"></el-table-column>
          <el-table-column prop="roleName" label="角色名称"></el-table-column>
          <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.id)">编辑</el-button>
              <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteEditDialog(scope.row.id)">删除</el-button>
              <el-button type="warning" icon="el-icon-setting" size="mini" @click="showSettingDialog(scope.row)">分配权限</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
<!--      添加角色对话框-->
      <el-dialog
      title="添加角色"
      :visible.sync="addRolesDialogVisible"
      width="50%"
      @close="addRolesClosed">
        <el-form :model="addRolesForm" :rules="addRolesFormRules" ref="addRolesRef" label-width="80px">
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="addRolesForm.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="addRolesForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRolesDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRolesInfo">确 定</el-button>
      </span>
      </el-dialog>
<!--      修改角色对话框-->
      <el-dialog
        title="修改角色"
        :visible.sync="editRolesDialogVisible"
        width="50%"
        @close="editRolesClosed">
        <el-form :model="editRolesForm" :rules="editRolesFormRules" ref="editRolesRef" label-width="80px">
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="editRolesForm.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="editRolesForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
        <el-button @click="editRolesDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRolesInfo">确 定</el-button>
      </span>
      </el-dialog>
      <!--      分配权限对话框-->
      <el-dialog
        title="分配权限"
        :visible.sync="settingRolesDialogVisible"
        width="50%"
        @close="setRightsDialogClosed">
<!--          树形控件-->
        <el-tree :data="rightsList" :props="treeProps"
                 show-checkbox
                 node-key="id"
                 default-expand-all
                 :default-checked-keys="defKeys"
                 ref="treeRef"
        ></el-tree>
        <span slot="footer" class="dialog-footer">
        <el-button @click="settingRolesDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
      </el-dialog>
    </div>
</template>

<script>
export default {
  name: 'Roles',
  created () {
    this.getRolesList()
  },
  data () {
    return {
      // 角色列表对象
      rolesList: [],
      // 添加用户对话框
      addRolesDialogVisible: false,
      addRolesForm: {
        roleName: '',
        roleDesc: ''
      },
      addRolesFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ]
      },
      // 修改角色对话框
      editRolesDialogVisible: false,
      editRolesForm: {},
      editRolesFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ]
      },
      // 分配权限对话框
      settingRolesDialogVisible: false,
      // 所有权限的数据
      rightsList: [],
      // 树形控件的属性绑定对象
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      // 默认选中节点id值的数组
      defKeys: [],
      // 保存分配角色的id
      roleId: ''
    }
  },
  methods: {
    async getRolesList () {
      const { data: res } = await this.$http.get('roles')
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户列表失败')
      }
      this.rolesList = res.data
    },
    // 根据id删除对应的权限
    async removeRightById (role, rightId) {
      const confirmResult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '删除权限', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // console.log(confirmResult)
      if (confirmResult !== 'confirm') {
        return this.$message.info('取消了删除')
      }
      const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
      if (res.meta.status !== 200) {
        return this.$message.error('删除权限失败')
      }
      // 删除成功后重新赋值给权限数据
      role.children = res.data
    },
    // 添加角色
    // addRoles () {
    //   this.addRolesDialogVisible = true
    // },
    // 表单重置
    addRolesClosed () {
      this.$refs.addRolesRef.resetFields()
    },
    // 添加角色
    addRolesInfo () {
      this.$refs.addRolesRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post('roles', this.addRolesForm)
        if (res.meta.status !== 201) {
          return this.$message.error('添加角色信息失败')
        }
        this.$message.success('添加角色信息成功')
        this.addRolesDialogVisible = false
        await this.getRolesList()
      })
    },
    // 修改对话框查询展示
    async showEditDialog (id) {
      const { data: res } = await this.$http.get('roles/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('查询用户信息失败')
      }
      this.editRolesForm = res.data
      this.editRolesDialogVisible = true
    },
    // 表单重置
    editRolesClosed () {
      this.$refs.editRolesRef.resetFields()
    },
    // 修改提交
    editRolesInfo () {
      this.$refs.editRolesRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put('roles/' + this.editRolesForm.roleId, { roleName: this.editRolesForm.roleName, roleDesc: this.editRolesForm.roleDesc })
        if (res.meta.status !== 200) return this.$message.error('修改角色失败')
        this.editRolesDialogVisible = false
        this.$message.success('修改角色成功')
        await this.getRolesList()
      })
    },
    // 删除角色列表
    async deleteEditDialog (id) {
      // 弹窗询问是否删除
      const result = await this.$confirm('此操作将永久删除该文件, 是否继续?', '删除角色', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // console.log(result)
      if (result !== 'confirm') {
        return this.$message.info('取消了删除')
      }
      const { data: res } = await this.$http.delete('roles/' + id)
      if (res.meta.status !== 200) return this.$message.error('删除角色失败')
      this.$message.success('删除角色成功')
      await this.getRolesList()
    },
    // 表单重置
    // settingRolesClosed () {
    //   this.defKeys = []
    // },
    // 分配权限
    async showSettingDialog (role) {
      this.roleId = role.id
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) return this.$message.error('获取权限失败')
      this.rightsList = res.data
      // 对话框打开后展示默认勾选项
      this.getLeafkeys(role, this.defKeys)
      this.settingRolesDialogVisible = true
    },
    // 通过递归 获取角色下三级权限的 id, 并保存到defKeys数组
    getLeafkeys (node, arr) {
      // 没有children属性，则是三级节点
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => this.getLeafkeys(item, arr))
    },
    // 分配权限对话框的关闭
    setRightsDialogClosed () {
      // defKeys数组重置
      this.defKeys = []
    },
    // 分配权限保存
    async allotRights () {
      // getCheckedKeys 返回目前被选中的节点的 key 所组成的数组
      // getHalfCheckedKeys 返回目前半选中的节点的 key 所组成的数组
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      // 把数组中的所有元素放入一个字符串
      const idStr = keys.join(',')
      console.log(idStr)
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: idStr })
      if (res.meta.status !== 200) return this.$message.error('分配权限失败')
      this.$message.success('分配权限成功')
      await this.getRolesList()
      this.settingRolesDialogVisible = false
    }
  }
}
</script>

<style scoped>
  .el-tag {
    margin: 7px;
  }
.bdbottom {
  border-bottom: 1px solid #eee;
}
.bdtop {
  border-top: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
